<?php
/**************************************************************************
 *
 *   Copyright 2010 American Public Media Group
 *
 *   This file is part of AIR2.
 *
 *   AIR2 is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   AIR2 is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with AIR2.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************/

require_once 'AIR2_CRUD_Controller.php';

/**
 * Home Controller -- homepage for AIR2
 *
 * @author rcavis
 * @package default
 */
class Home_Controller extends AIR2_CRUD_Controller {
    /* AIR2_CRUD_Controller variables */
    public $column_whitelist = array('tank_actm_id');
    public $exposed_relations = array(
        'users' => 'User',
        'projects' => 'Project',
        'inquiries' => 'Inquiry',
        'saved_searches' => 'SavedSearch',
        'imports' => 'Tank'
    );

    /* Query for getting a user's projects */
    // TODO test this vis-a-vis query_may_read()
    private static $Q_PRJ = 'SELECT q1.porg_prj_id FROM ProjectOrg q1 WHERE q1.porg_org_id IN (SELECT q2.uo_org_id FROM UserOrg q2 WHERE q2.uo_user_id = ?)';

    /**
     * Add custom relations to queries to this controller
     *
     * @param AIR2_Query $q
     * @param boolean $deeply (optional)
     */
    protected function _add_query_load_related(&$q, $deeply=true) {
        if ($this->rel_uri == 'users') {
            $q->leftJoin('a.UserOrg uo WITH uo.uo_home_flag = true');
            $q->leftJoin('uo.Organization o');
        }
        elseif ($this->rel_uri == 'projects') {
            $q->where('a.prj_status != ?', 'X');  // TODO instead in query_may_read etc ??
            $q->orderBy('a.prj_upd_dtim DESC');
            $q->addOrderBy('a.prj_upd_dtim DESC');
        }
        elseif ($this->rel_uri == 'inquiries') {
            $q->leftJoin('a.CreUser c');
            $q->leftJoin('c.UserOrg uo WITH uo.uo_home_flag = true');
            $q->leftJoin('uo.Organization o');
            $q->orderBy('a.inq_cre_dtim DESC');
            $q->getRoot()->setAttribute(Doctrine_Core::ATTR_QUERY_LIMIT, Doctrine_Core::LIMIT_ROWS);
            $recv_count = '(select count(*) from src_response_set where srs_inq_id = a.inq_id) as ReceivedCount';
            $sent_count = '0 as SentCount'; // TODO
            $q->select("a.*, c.*, u.*, uo.*, o.*, $recv_count, $sent_count");
            $this->extra_field_defs []= array('name' => 'SentCount', 'type' => 'int');
            $this->extra_field_defs []= array('name' => 'ReceivedCount', 'type' => 'int');

            // restrict to user's projects --- IF NOT system user
            if (AIR2_REMOTE_USER_TYPE != 'S') {
                $s1 = self::$Q_PRJ;
                $s2 = "SELECT i.pinq_inq_id from ProjectInquiry i WHERE i.pinq_prj_id IN ($s1)";
                $q->andWhere("a.inq_id IN ($s2)", 6);
            }
        }
        elseif ($this->rel_uri == 'saved_searches') {

        }
        elseif ($this->rel_uri == 'imports') {
            $q->orderBy('a.tank_upd_dtim DESC');
        }

        parent::_add_query_load_related($q, $deeply);
    }


    /**
     * Override index() to only allow HTML view of the homepage
     */
    function index() {
        if ($this->response_view != 'html') {
            $this->show_415();
        }

        $q = $this->build_query(null, 'users');
        $q->where('user_type != "S"');
        $q->limit(8);
        $usr_data = $this->fetch_data($q, true, true);

        $q = $this->build_query(null, 'projects');
        $q->limit(8);
        $prj_data = $this->fetch_data($q, true, true);

        $q = $this->build_query(null, 'inquiries');
        $q->limit(6);
        $inq_data = $this->fetch_data($q, true, true);

        $q = $this->build_query(null, 'saved_searches');
        $q->limit(5);
        $ss_data = $this->fetch_data($q, true, true);

        $q = $this->build_query(null, 'imports');
        $q->limit(5);
        $imp_data = $this->fetch_data($q, true, true);

        $q = $this->build_query(null, 'imports');
        $q->leftJoin('a.User u');
        $q->addWhere('tank_status = ?', Tank::$STATUS_DISCRIM_ERRORS);
        $q->limit(5);
        $alt_data = $this->fetch_data($q, true, true);

        $home = $this->load->view(
            'home',
            array(
                'users' => $usr_data,
                'projs' => $prj_data,
                'inqs'  => $inq_data,
                'saved_searches' => $ss_data,
                'imports' => $imp_data,
                'alerts' => $alt_data,
            ),
            true
        );

        $this->response(
            array(
                'head' => array('title' => AIR2_SYSTEM_DISP_NAME.' Home'),
                'body' => $home,
            )
        );
    }


}
